package cn.kgc.countservice.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RedisDaoImpl implements RedisDao{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *  Redis的数据类型HyperLogLog在接收到IP地址后会把他计算成一个数（看不到）存储起来
     *  下次接收到IP地址时依旧会计算成一个数并自动校验是否存在（去重），若不存在则存储否则不存储
     */
    @Override
    public Integer hyperLogAdd(String key, String value) {
        return stringRedisTemplate.opsForHyperLogLog().add(key, value).intValue();
    }

    @Override
    public Integer hyperLogCount(String key) {
        return stringRedisTemplate.opsForHyperLogLog().size(key).intValue();
    }

    @Override
    public List<Integer> getHotNews(List<Integer> newsIdList) {
        for(Integer newsId : newsIdList){
            Integer count = hyperLogCount("ip:" + newsId);
            stringRedisTemplate.opsForZSet().add("hotList",newsId+"",count);
        }
        Set<String> result = zSetSorted("hotList", 0, 9);
        List<Integer> list = new ArrayList<>();
        for(String s : result){
            list.add(Integer.parseInt(s));
        }
        return list;
    }

    @Override
    public long zSetRemove(String key, Integer min, Integer max) {
        return stringRedisTemplate.opsForZSet().removeRange(key,(long)min,(long)max);
    }

    public Set<String> zSetSorted(String key, Integer minId, Integer maxId){
        return stringRedisTemplate.opsForZSet().reverseRange(key, minId, maxId);
    }

    @Override
    public void setHot(String key, String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    @Override
    public String getHot(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
}
